const Koa = require('koa')
const app = new Koa() // 实例化
const jwt = require('jsonwebtoken')
const koaBody = require('koa-body')
const koaStatic = require('koa-static')
const path = require('path')
// const bodyParser = require('koa-bodyparser')

const users = require('./routes/users')
const blogs = require('./routes/blogs')
const upload = require('./routes/upload')

// app.use(bodyParser())

//封装一个获取参数的全局中间件
app.use(async (ctx, next) => {
	console.log('GET参数', ctx.query)
	console.log('POST参数', ctx.request.body)
	await next()
})
// console.log(path.join(__dirname, 'public'), 'path.join(__dirname') /
//  http://localhost:3000/public/uploads/upload_3a87ebf3329c913ec84ee6e6ec68f86f.jpeg
app.use(koaStatic(path.join(__dirname, 'public')))

// 解析 图片格式
app.use(
	koaBody({
		multipart: true, // 启用文件格式
		formidable: {
			uploadDir: path.join(__dirname, '/public/uploads'), // 设置上传路径
			keepExtensions: true // 保留扩展名 默认false 1.png
		} // 一个上传文件的包
	})
)
const whiteList = ['/api/signIn', '/api/blogs']

// 登陆校验中间件
const signMiddleware = async (ctx, next) => {
	// ctx.path == url
	console.log(whiteList.includes(ctx.path), ctx.path, '----')
	if (whiteList.includes(ctx.path)) {
		console.log('跳过中间件')
		await next() // 找到了
	} else {
		try {
			// 1. 找token（）并且解析token
			const { token } = ctx.request.headers
			const userInfo = jwt.verify(token, '1904-secret')
			// 2. 如果想接着继续使用这个用户信息
			ctx.state.userInfo = userInfo // 传递信息
			await next()
		} catch (err) {
			ctx.body = { code: 401, err }
		}
	}
}
// 全局中间件
// app.use(signMiddleware) // 解析token
// app.use(auth) // 校验token
// upload
app.use(users.routes(), users.allowedMethods())
app.use(blogs.routes(), blogs.allowedMethods())
app.use(upload.routes(), upload.allowedMethods())

app.listen(3000, () => {
	console.log(`http://localhost:3000`)
})
